package com.thread.jucTest;

import org.junit.Test;

import java.util.concurrent.Semaphore;

/**
 * @program: leetcode
 * @description:
 * @author: wangzhihua
 * @date: 2024-06-22
 */
public class ConcurrentTest {

	@Test
	public void test1() {
		Semaphore semaphore = new Semaphore(3);
		for (int i = 0; i < 6; i++) {
			new Thread(() -> {
				try {
					System.out.println(Thread.currentThread().getName() + " 申请一个信号量");
					semaphore.acquire();
					System.out.println(Thread.currentThread().getName() + " 信号量已拿到");
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					semaphore.release();
					System.out.println(Thread.currentThread().getName() + " 信号量已释放 剩余信号量" + semaphore.availablePermits());
				}
			}, String.valueOf(i)).start();
		}
		try {
			Thread.sleep(20000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}
